package com.cinema.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 图片访问Servlet
 */
public class ImageServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.length() <= 1) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        // 移除开头的斜杠
        String imagePath = pathInfo.substring(1);
        
        // 构建完整的文件路径
        String realPath = getServletContext().getRealPath("/images/" + imagePath);
        Path path = Paths.get(realPath);
        
        // 检查文件是否存在
        if (!Files.exists(path) || !Files.isRegularFile(path)) {
            // 如果文件不存在，返回默认图片
            String defaultImagePath = getServletContext().getRealPath("/images/default-poster.jpg");
            path = Paths.get(defaultImagePath);
            
            if (!Files.exists(path)) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }
        
        // 设置响应头
        String contentType = getServletContext().getMimeType(path.toString());
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        response.setContentType(contentType);
        
        // 设置缓存头
        response.setHeader("Cache-Control", "public, max-age=31536000"); // 1年
        response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L);
        
        // 输出文件内容
        try (InputStream inputStream = Files.newInputStream(path);
             OutputStream outputStream = response.getOutputStream()) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}
